//
//  NSString+IMTExtension.m
//  MusicLamp
//
//  Created by lorin on 15/3/17.
//  Copyright (c) 2015年 imt_ios_group. All rights reserved.
//

#import "NSString+IMTExtension.h"
#import "NSData+MMExtension.h"
#import "GTMBase64.h"
#import "WBCDESUtil.h"
#import "MGConstFile.h"

#import <objc/runtime.h>

#ifdef WF_SANDBOX

static NSString *k_Qi_Niu_Host_Flag = @"clouddn.com";
#else
static NSString *k_Qi_Niu_Host_Flag = @"images.irulu.com";
#endif

static NSInteger const k_Password_Mini_Length = 6;

@implementation NSString (IMTExtension)

- (BOOL)isBlank
{
    if (self == nil || self == NULL)
    {
        return YES;
    }
    
    if ([self isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
    {
        return YES;
    }
    
    return NO;
}
-(BOOL)isMobliePhoneNumber
{
    if (self.length == 0) {
        return NO;
    }
    NSString *match = @"^[+]?[\\d|-]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",match];
    BOOL isMatch = [predicate evaluateWithObject:self];
    return isMatch;
}

-(BOOL)isValidSMSVerifyCode
{
    if (self.length == 0) {
        return NO;
    }
    NSString *match = @"^\\d{4,6}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",match];
    BOOL isMatch = [predicate evaluateWithObject:self];
    return isMatch;
}

-(BOOL)isEmail
{
    if (self.length == 0) {
        return NO;
    }
    NSString *match = @"[\\w!#$%&\'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&\'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",match];
    BOOL isMatch = [predicate evaluateWithObject:self];
    return isMatch;
}


-(BOOL)isURLPath
{
    NSString *match = @"^http(s)?://[^\\s]*";
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:match options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger matchResult = [regex numberOfMatchesInString:self options:NSMatchingReportCompletion range:NSMakeRange(0, self.length)];
    
    return matchResult == 1;
}
- (NSString *)URLEncodedString
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)self,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

//-(NSDictionary *)getURLParams
//{
//    NSURL *url = [NSURL URLWithString:self];
//    
//    return [url wf_ParamsDic];
//}

//-(NSString *)adjustPasswordMD5Hash
//{
//    return [[NSString stringWithFormat:@"%@:%@",self,k_WF_Password_Prefix] md5Hash];
//}

//-(NSString *)getPinYin
//{
//    return [ISSPYMethod getPinYin:self];
//}
//
//-(NSString *)getPinYinFirstChar
//{
//    return [NSString  stringWithFormat:@"%c",[ISSPYMethod getFirstName:self locale:YES]];
//}



-(NSString *)encryptUseDESWithKey:(NSString *)key
{
    return [WBCDESUtil encryptUseDES:self key:key];
}

-(NSString *)decryptUseDESWithKey:(NSString *)key
{
    return [WBCDESUtil decryptUseDES:self key:key];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString*)md5Hash {
    return [[self dataUsingEncoding:NSUTF8StringEncoding] md5Hash];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString*)sha1Hash {
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1Hash];
}

-(NSString *)base64String
{
    NSData * strData = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [GTMBase64 stringByEncodingData:strData];
}


-(UIColor *)tintColor{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setTintColor:(UIColor *)tintColor{
    objc_setAssociatedObject(self, @selector(tintColor), tintColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - adjust qiniu image size
- (NSURL *)adjust2SmallImageUrl
{
    return [self adjustQiNiuImageSizeUrl:SCREEN_WIDTH/2];
}

- (NSURL *)adjust2MiddleImageUrl
{
    return [self adjustQiNiuImageSizeUrl:SCREEN_WIDTH];
}

- (NSURL *)adjust2LargeImageUrl
{
    return [self adjustQiNiuImageSizeUrl:SCREEN_WIDTH*1.5];
}

- (NSURL *)adjustQiNiuImageSizeUrl:(NSInteger)width
{
    NSURLComponents *urlComponents = [NSURLComponents componentsWithString:self];
    if (!urlComponents.host || [urlComponents.host rangeOfString:k_Qi_Niu_Host_Flag].location == NSNotFound) {
        return urlComponents.URL;
    }
    
    if (urlComponents.scheme) {
        urlComponents.query = [NSString stringWithFormat:@"imageView2/2/w/%@/interlace/1",@(width)];
        return urlComponents.URL;
    }
    return nil;
}

- (NSString *)adjust2SmallImageUrlString
{
    NSURL *url = [self adjust2SmallImageUrl];
    return url ? url.absoluteString : self;
}

- (NSString *)adjust2MiddleImageUrlString
{
    NSURL *url = [self adjust2MiddleImageUrl];
    return url ? url.absoluteString : self;
}

- (NSString *)adjust2LargeImageUrlString
{
    NSURL *url = [self adjust2LargeImageUrl];
    return url ? url.absoluteString : self;
}

#pragma mark - CreditCard format
- (NSString *)formatCreditCardNumber {
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    NSString *clearedString = [self clearCreditCardNumberFromat];
    
    if (clearedString.length >= 16) {
        clearedString = [clearedString substringWithRange:NSMakeRange(0, 16)];
    }
    
    NSString *newString = @"";
    while (clearedString.length > 0) {
        NSString *subString = [clearedString substringToIndex:MIN(clearedString.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        clearedString = [clearedString substringFromIndex:MIN(clearedString.length, 4)];
    }
    
    return [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
}

- (NSString *)clearCreditCardNumberFromat {
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

//#pragma mark - verify
//- (NSString *)verifyEmail
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.email", nil);
//    }
//    
//    if (![self isEmail]) {
//        return WF_STR(@"verify.email.wrong.format", nil);
//    }
//    
//    return nil;
//}
//
- (NSString *)verifyPassword
{
    return [self verifyPasswordWithMiniLenght:YES];
}
//
- (NSString *)verifyPasswordWithMiniLenght:(BOOL)checkMiniLenght
{
    if ([self isBlank]) {
        return @"您输入的密码为空";
    }
    
    if (checkMiniLenght && [self length] < k_Password_Mini_Length) {
        return [NSString stringWithFormat:@""];
    }
    
    //TODO: 验证组成
    
    return nil;
}
//
//- (NSString *)verifyAgainpasswordWithMiniLenght{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.isempty.againpassword", nil);
//    }
//    
//    if ([self length] < k_Password_Mini_Length) {
//        return [NSString stringWithFormat:WF_STR(@"verify.againpassword.wrong.lenght", nil),@(k_Password_Mini_Length)];
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyCurrentpassword{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.isempty.current.password", nil);
//    }
//    return nil;
//}
//
//- (NSString *)verifyNewpassword{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.isempty.new.password", nil);
//    }
//    
//    if ([self length] < k_Password_Mini_Length) {
//        return [NSString stringWithFormat:WF_STR(@"verify.password.wrong.lenght", nil),@(k_Password_Mini_Length)];
//    }
//    return nil;
//}
//
//- (NSString *)verifyCurrentPasswordWith:(NSString *)newPassword{
//    if ([self isEqualToString:newPassword]) {
//        return WF_STR(@"verify.password.same.compare", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyConfirmpasswordWithMiniLenght{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.isempty.confirm.password", nil);
//    }
//    
//    if ([self length] < k_Password_Mini_Length) {
//        return [NSString stringWithFormat:WF_STR(@"verify.confirm.password.wrong.lenght", nil),@(k_Password_Mini_Length)];
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyConfirmPasswordWith:(NSString *)password
//{
//    if (![self isEqualToString:password]) {
//        return WF_STR(@"verify.password.wrong.compare", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifySearchKeyword
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.keyword", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyContactName
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.conactname", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyStreet
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.street", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyCity
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.city", nil);
//    }
//    
//    return nil;
//}
//
//
//- (NSString *)verifyState
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.province", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyPostalCode
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.postalcode", nil);
//    }
//    
//    return nil;
//}
//
//
//- (NSString *)verifyPhoneNumber
//{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.phone.number", nil);
//    }
//    
//    if (![self isMobliePhoneNumber]) {
//        return WF_STR(@"verify.phone.number.wrong.format", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyFirstName{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.firstname", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyLastName{
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.lastname", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyFeedback {
//    if ([self isBlank]) {
//        return WF_STR(@"verify.is.empty.feedback", nil);
//    }
//    
//    return nil;
//}
//
//- (NSString *)verifyStringWithMaxLenght:(NSInteger)maxLenght{
//    if ([self length] > maxLenght) {
//        return [self verifyStringWithoutCheckMaxLenght:maxLenght];
//    }
//    return nil;
//}
//
//-(NSString *)verifyStringWithoutCheckMaxLenght:(NSInteger)maxLenght{
//    return [NSString stringWithFormat:WF_STR(@"can.not.more.than", nil),@(maxLenght)];
//}
//
//
//
//+ (NSString *)makeINT32Random
//{
//    u_int32_t random = arc4random_uniform(INT32_MAX);
//    return [NSString stringWithFormat:@"%@",@(random)];
//}
@end
